package com.sreManager.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sreManager.domain.CompanyBuilding;
import com.sreManager.domain.CompanyEstimate;
import com.sreManager.domain.CompanyIncharge;
import com.sreManager.mapper.CompanyBuildingMapper;
import com.sreManager.mapper.CompanyEstimateMapper;
import com.sreManager.mapper.CompanyInchargeMapper;
import com.sreManager.model.BuildingModel;

@Service
public class BuildingService {

	@Autowired CompanyInchargeMapper inchargeMapper;

	@Autowired CompanyEstimateMapper estimateMapper;

	@Autowired CompanyBuildingMapper buildingMapper;

	@Transactional
	public void insert(BuildingModel buildingModel) {
    	CompanyBuilding building = buildingModel.getBuildingDao();
		buildingMapper.insertBuilding(building);

    	Integer buildingCd = building.getBuildingCd();
	    insertIncharge(buildingModel.getBuildingDao().getIncharge(), buildingCd);
	    insertEstimate(buildingModel.getBuildingDao().getEstimate(), buildingCd);
	}

	@Transactional
	public void update(BuildingModel buildingModel) {
    	CompanyBuilding building = buildingModel.getBuildingDao();
		buildingMapper.updateBuilding(building);

    	Integer buildingCd = building.getBuildingCd();
	    insertIncharge(buildingModel.getBuildingDao().getIncharge(), buildingCd);
	    insertEstimate(buildingModel.getBuildingDao().getEstimate(), buildingCd);

	    List<Integer> inchargeCdList = buildingModel.getInchargeCd();
	    if(inchargeCdList!=null) inchargeMapper.deleteIncharges(inchargeCdList, buildingCd);
	    List<Integer> estimateCdList = buildingModel.getEstimateCd();
	    if(estimateCdList!=null) estimateMapper.deleteEstimates(estimateCdList, buildingCd);
	}

	private void insertEstimate(List<CompanyEstimate> estimateList, Integer buildingCd) {
		for(CompanyEstimate estimate : estimateList){
			estimate.setBuildingCd(buildingCd);

			if(estimate.getEstimateCd()==null){
				estimateMapper.insertEstimate(estimate);
			}else{
				estimateMapper.updateEstimate(estimate);
			}
		}
	}

	private void insertIncharge(List<CompanyIncharge> inchargeList, Integer buildingCd) {
		for(CompanyIncharge incharge : inchargeList){
			incharge.setBuildingCd(buildingCd);

			if(incharge.getInchargeCd()==null){
				inchargeMapper.insertIncharge(incharge);
			}else{
				inchargeMapper.updateIncharge(incharge);
			}
		}
	}

	@Transactional
	public int deleteAllData() {
		int code = inchargeMapper.deleteIncharge(null);
		code = estimateMapper.deleteEstimate(null);
		code = buildingMapper.deleteBuilding(null);
		return code;
	}
}
